package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.yh.common.utils.DateUtils;
import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.Page;
import com.yh.correct.model.Personnel;
import com.yh.correct.model.Project;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.ICorrectedPersonService;
import com.yh.correct.service.IPersonnelService;
import com.yh.correct.service.IProjectService;

/**
 * 矫正方案登记控制层
 * 
 * @author 陈帅
 */
@RestController
@RequestMapping("/project")
public class ProjectController {

	private static Logger logger = LogManager.getLogger(ProjectController.class);
	@Autowired
	private IProjectService projectService;

	@Autowired
	private ICorrectedPersonService correctedPersonService;

	/**
	 * 首页跳转
	 * 
	 * @return
	 */
	@RequestMapping(value="/skip")
	public ModelAndView skip(){ 
		return new ModelAndView("education/project");
	}
	/**
	 * 调取别人的业务层，获取别人表中的矫正人员列表
	 * 
	 * @author 陈帅
	 */
	@RequestMapping(value = "/showCorrect")
	public List<Map<String, Object>> showCorrect() {

		List<Map<String, Object>> list = null;
		try {
			list = correctedPersonService.getAllCorrectedPerson();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(list);
		return list;
	}
	/**
	 * 根据id查询单个矫正方案
	 * 
	 * @author 陈帅
	 * @throws Exception 
	 */
	@RequestMapping(value = "/get")
	public ModelAndView getProject(Project p) throws Exception {
		logger.info("查询矫正登记" + p);
		Map<String, Object> map = projectService.getProject(p);
		return new ModelAndView("education/project_edit", map);
	}

	/**
	 * 添加矫正方案
	 * @throws Exception 
	 */
	@RequestMapping(value = "/add")
	public ResultData addProject(Project p) throws Exception {
		 //String date 页面传过来的"参数";
		//p.setProject_date(DateUtils.parseDate(date));
		int i = projectService.addProject(p);
		ResultData rd = new ResultData();
		if (i > 0) {
			rd.setCode(0);
			rd.setMessage("插入成功！");
		} else {
			rd.setCode(-1);
			rd.setMessage("插入失败");
		}

		return rd;
	}

	/**
	 * 删除矫正方案
	 * @throws Exception 
	 */
	@RequestMapping(value = "/del")
	public ResultData del(Project p) throws Exception {
		logger.debug("删除矫正方案" + p);
		int i = projectService.delProject(p);
		ResultData rd = new ResultData();
		if (i > 0) {
			rd.setCode(0);
			rd.setMessage("删除成功！");
		} else {
			rd.setCode(-1);
			rd.setMessage("删除失败");
		}
		return rd;
	}

	/**
	 * 修改矫正方案
	 * @throws Exception 
	 */
	@RequestMapping(value = "/edit")
	public ResultData edit(Project p) throws Exception {
		 //String date
		//p.setProject_date(DateUtils.parseDate(date));
		int i = projectService.editProject(p);
		ResultData rd = new ResultData();
		if (i > 0) {
			rd.setCode(0);
			rd.setMessage("修改成功！");
		} else {
			rd.setCode(-1);
			rd.setMessage("修改失败");
		}
		return rd;
	}

	/**
	 * 模糊查询矫正方案
	 * @throws Exception 
	 */
	@RequestMapping(value = "/getLike")
	public ResultData getLikeProjects(String name, String date,Integer pageSize,Integer pageNum) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pdName", name);
		map.put("likedate", date);
		map.put("pageSize", pageSize);
		map.put("pageNum",pageNum);
		Page page = projectService.getLikeProjects(map);
		ResultData rd = new ResultData();
		List<Object> list = new ArrayList<Object>();
		if (page != null) {
			list.add(page);
			rd.setCode(0);
			rd.setMessage("查询成功！");
			rd.setData(list);
		} else {
			rd.setCode(-1);
			rd.setMessage("查询失败！");
		}
		return rd;
	}


	/**
	 * 适用于添加表中的视图渲染
	 * 
	 * @author 陈帅
	 */
	@RequestMapping("/addView")
	public ModelAndView add() {
		return new ModelAndView("education/project_add");
	}

	/**
	 * 获取别人表中的工作人员列表
	 * 
	 * @author 陈帅
	 * @throws Exception 
	 */
	@RequestMapping(value = "/showPerson")
	public ResultData showPerson(Personnel p) throws Exception {
		List<Personnel> list = null;
		list = projectService.getPersonnel(p);
		ResultData rd = new ResultData();
		if (list != null) {
			rd.setCode(0);
			rd.setMessage("查询成功！");
			rd.setData(list);
		} else {
			rd.setCode(-1);
			rd.setMessage("查询失败！");
		}
		return rd;
	}
	
	/**
	 * 导出Excle
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/excel")
	public String outExcle(HttpServletRequest request, HttpServletResponse response){
		String fileName = "矫正方案登记文件";
		List<Map<String, Object>> projects = outData();
		List<Map<String, Object>> list = outExcelRecord(projects);
		String columnNames[] = { "编号", "矫正单位", "姓名", "工作人员", "矫正日期", "状态",};
		String keys[] = { "id", "jdName", "pdName", "pName", "project_date", "state"};
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		try {
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			try {
				throw e;
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			if (bis != null)
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return null;
	}
	/**
	 * 导出Excle时获取所有信息
	 * 
	 * @return
	 */
	private List<Map<String, Object>> outData(){
		// TODO Auto-generated method stub
		List<Map<String, Object>> list = null;
		try {
			list = projectService.getAllP();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * 记录要导出的所有信息
	 * 
	 * @param projects
	 * @return
	 */
	private List<Map<String, Object>> outExcelRecord(List<Map<String, Object>> projects){
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		listmap.add(map);
		Map<String, Object> object = null;
		for (int j = 0; j < projects.size(); j++) {
			object = projects.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("id", object.get("id"));
			mapValue.put("jdName", object.get("jdName"));
			mapValue.put("pdName", object.get("pdName"));
			mapValue.put("pName", object.get("pName"));
			mapValue.put("project_date", object.get("project_date"));
			mapValue.put("state", object.get("state"));
			listmap.add(mapValue);
		}
		return listmap;
	}

}
